package com.bosssoft.hr.train.j2se.file;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import lombok.extern.slf4j.Slf4j;
import java.io.File;



/**
 * @Classname: OssFileUitls
 * @Description:该类用于实现文件上传云存储
 * @author: zoubinyan
 * @Date: 2023/2/22
 */
@Slf4j
public class OssFileUitls {

     public void upload(File file) {
         /**
          * Endpoint以华东1（杭州）为例，其它Region请按实际情况填写
          * 这里我用的是上海的
          */
         String endpoint = "https://oss-cn-shanghai.aliyuncs.com";
         /**
          * 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户
          */
         String accessKeyId = "LTAI5tQN2WzfRQkejyBMuQrb";
         String accessKeySecret = "0utQ5KcBa8czZonfitAVRccm3w92CS";
         /**
          * 填写Bucket名称，例如examplebucket
          */
         String bucketName = "mybucket";
         /**
          * 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt
          */
         String objectName = "F:\\新建文件夹 (2)\\java-master\\pom.xml";
         /**
          * 填写本地文件的完整路径，例如D:\\localpath\\examplefile.txt
          * 如果未指定本地路径，则默认从示例程序所属项目对应本地路径中上传文件
          */
         String filePath= file.getPath();

         /**
          * 创建OSSClient实例
          */
         OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

         try {
             /**
              * 创建PutObjectRequest对象
              */
             PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, new File(filePath));
             /**
              * 上传文件
              */
             ossClient.putObject(putObjectRequest);
         } catch (OSSException oe) {
             log.info("Caught an OSSException, which means your request made it to OSS, "
                     + "but was rejected with an error response for some reason.");
             log.info("Error Message:" + oe.getErrorMessage());
             log.info("Error Code:" + oe.getErrorCode());
             log.info("Request ID:" + oe.getRequestId());
             log.info("Host ID:" + oe.getHostId());
         } catch (ClientException ce) {
             log.info("Caught an ClientException, which means the client encountered "
                     + "a serious internal problem while trying to communicate with OSS, "
                     + "such as not being able to access the network.");
             log.info("Error Message:" + ce.getMessage());
         } finally {
             if (ossClient != null) {
                 ossClient.shutdown();
             }
         }
     }
}
